/*
 * 文件名：InfoHandler.java
 * 版权：Copyright 2012-2016 YLINK Tech. Co. Ltd. All Rights Reserved. 
 * 描述： InfoHandler.java
 * 修改人：lizhi 1708029
 * 修改时间：2019年10月18日
 * 修改内容：新增
 */
package com.lizhi.yun.core.eureka.handler;
/**
 * @Title:  InfoHandler.java
 * @Package: com.cloud.info.handller.InfoHandler.java
 * @Description: Eureka服务操作
 * @Company: ylink
 * @author  lizhi 
 * @date  2019年10月18日 上午11:52:49
 */

import com.lizhi.common.yun.entity.ListResponseResult;
import com.lizhi.utils.PropertiesUtil;
import com.lizhi.utils.StringUtils;
import com.lizhi.utils.httprequest.HttpRequestUtils;
import com.lizhi.utils.json.SamJsonUtil;
import com.lizhi.utils.shell.GanymedUtils;
import com.lizhi.utils.shell.ShellResult;
import com.lizhi.yun.base.BaseHandler;
import com.lizhi.common.yun.entity.InstancePOJO;
import com.lizhi.yun.core.eureka.pojo.RegistryPOJO;
import com.lizhi.yun.db.dao.UppParametersDao;
import com.lizhi.yun.db.pojo.UppParametersPOJO;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EurekaInfoHandler extends BaseHandler {

    @Resource
	private EurekaClient eurekaClient;
	
	@Autowired
	private DiscoveryClient discoveryClient;

	@Resource
	private UppParametersDao uppParametersDao;
	

	/**
	 * 获取所有的服务列表
	 * @return
	 */
	public ListResponseResult getDeploys(Map<String, Object> map) {
		String serviceId = map.get("serviceId").toString();
		String port = map.get("port").toString();
		List<InstancePOJO> result = new ArrayList<InstancePOJO>();
		List<String> listServiceNames = this.discoveryClient.getServices();
		for (String serviceName : listServiceNames) {
			String services = PropertiesUtil.getProperties("pass.services", "system");
			if (!services.contains(serviceName.toUpperCase())){
				List<InstanceInfo> instances = eurekaClient.getInstancesByVipAddress(serviceName, true);
				for (InstanceInfo instance : instances) {
					InstancePOJO instanceDO = new InstancePOJO();
					instanceDO.setServiceId(instance.getAppName());
					UppParametersPOJO uppParametersPOJO = uppParametersDao.selectById(instanceDO.getServiceId().toLowerCase());
					if (!StringUtils.isEmpty(uppParametersPOJO)){
						instanceDO.setServiceName(uppParametersPOJO.getVal());
					}
					instanceDO.setHost(instance.getIPAddr());
					instanceDO.setPort(String.valueOf(instance.getPort()));
					instanceDO.setState(instance.getStatus().name());
					instanceDO.setHomePageUrl(instance.getHomePageUrl());
					if (!StringUtils.isEmpty(serviceId) || !StringUtils.isEmpty(port)){
						if (!StringUtils.isEmpty(serviceId) && !StringUtils.isEmpty(port)){
							if (serviceId.toUpperCase().equals(instanceDO.getServiceId().toUpperCase()) && port.equals(instanceDO.getPort())){
								result.add(instanceDO);
							}
						} else if (!StringUtils.isEmpty(serviceId)){
							if (serviceId.toUpperCase().equals(instanceDO.getServiceId().toUpperCase())){
								result.add(instanceDO);
							}
						} else if (!StringUtils.isEmpty(port)){
							if (port.equals(instanceDO.getPort())){
								result.add(instanceDO);
							}
						}
					} else {
						result.add(instanceDO);
					}
				}
			}
		}
		Integer pageIndex = Integer.valueOf((String) map.get("pageIndex"));
		Integer pageSize = Integer.valueOf((String) map.get("pageSize"));

		Integer start = (pageIndex - 1) * pageSize;
		Integer end = pageIndex * pageSize;
		List<InstancePOJO> list = new ArrayList<InstancePOJO>();
		if (result.size() > end){
			for (int i = start; i < end; i++){
				list.add(result.get(i));
			}
		} else {
			for (int i = start; i < result.size(); i++){
				list.add(result.get(i));
			}
		}
		return getListResult(result.size(), list, map);
	}


	public List<InstancePOJO> getOtherDeploys(String appName) {
		List<InstancePOJO> result = new ArrayList<InstancePOJO>();
		List<String> listServiceNames = this.discoveryClient.getServices();
		for (String serviceName : listServiceNames) {
			List<InstanceInfo> instances = eurekaClient.getInstancesByVipAddress(serviceName, false);
			for (InstanceInfo instance : instances) {
				if (appName.toUpperCase().equals(instance.getAppName().toUpperCase())){
					InstancePOJO instanceDO = new InstancePOJO();
					instanceDO.setServiceId(instance.getAppName());
					instanceDO.setHost(instance.getIPAddr());
					instanceDO.setPort(String.valueOf(instance.getPort()));
					instanceDO.setState(instance.getStatus().name());
					instanceDO.setHomePageUrl(instance.getHomePageUrl());
					result.add(instanceDO);
				}
			}
		}
		return result;
	}

	public List<InstancePOJO> getGatewayDeploys(String appName) {
		List<InstancePOJO> result = new ArrayList<InstancePOJO>();
		List<String> listServiceNames = this.discoveryClient.getServices();
		for (String serviceName : listServiceNames) {
			List<InstanceInfo> instances = eurekaClient.getInstancesByVipAddress(serviceName, false);
			for (InstanceInfo instance : instances) {
				if ("SAMPLE-GATEWAY-SERVER".equals(instance.getAppName().toUpperCase())){
					InstancePOJO instanceDO = new InstancePOJO();
					instanceDO.setServiceId(instance.getAppName());
					instanceDO.setHost(instance.getIPAddr());
					instanceDO.setPort(String.valueOf(instance.getPort()));
					instanceDO.setState(instance.getStatus().name());
					instanceDO.setHomePageUrl(instance.getHomePageUrl() + appName.toUpperCase());
					result.add(instanceDO);
				}
			}
		}
		return result;
	}

	
	/**
	 * 根据服务名和端口号获取每个服务的详细信息
	 * @param serviceName
	 * @param port
	 * @return
	 */
	public String getAllByDeploy(String serviceName, String addr, String port) {
		List<InstancePOJO> result = new ArrayList<InstancePOJO>();
		List<InstanceInfo> instances = eurekaClient.getInstancesByVipAddress(serviceName, false);
		for (InstanceInfo instance : instances) {
			if (String.valueOf(instance.getPort()).equals(port) && instance.getIPAddr().equals(addr)) {
                InstancePOJO instancePOJO = new InstancePOJO();
                instancePOJO.setPort(String.valueOf(instance.getPort()));
                instancePOJO.setServiceId(instance.getAppName());
                instancePOJO.setFileName(instance.getIPAddr() + ":" + instance.getPort());
                instancePOJO.setHost(instance.getIPAddr());
                instancePOJO.setState(instance.getStatus().toString());
				log.info("获取到的服务信息instancePOJO:{}",instancePOJO);
				result.add(instancePOJO);
			}
		}
		return SamJsonUtil.toJson(result);
	}
	
	/**
	 * 根据ip地址和端口号停止服务
	 * @param addr
	 * @param port
	 * @return
	 */
	public ListResponseResult handleStop(String addr, String port) {
		if (!StringUtils.isEmpty(addr) && !StringUtils.isEmpty(port)) {
			List<String> listServiceNames = this.discoveryClient.getServices();
			for (String serviceName : listServiceNames) {
				List<InstanceInfo> instances = eurekaClient.getInstancesByVipAddress(serviceName, false);
				for (InstanceInfo instance : instances) {
					if (addr.equals(instance.getIPAddr()) && port.equals(String.valueOf(instance.getPort()))) {
						log.info("停止的时候获取到的url地址:"+"http://"+addr+":"+port+"/actuator/service-registry");
						RegistryPOJO registryVO = new RegistryPOJO();
						registryVO.setStatus("DOWN");
						String httpPost = HttpRequestUtils.httpPost("http://actuator:actuator@"+addr+":"+port+"/actuator/service-registry", SamJsonUtil.toJson(registryVO), "application/json");

                        /*try {
                            //执行停止脚本
                            ShellResult shellResult = GanymedUtils.exec(addr, "userName", "password", "filePath", StandardCharsets.UTF_8);
                            result = shellResult.getResult();
                            log.info("获取到的输出结果shellResult:{}",shellResult);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }*/
                        return getListResult(httpPost);
					} 
				}
			}
		}
		return getListResult(0, false);
	}

	/**
	 * 服务上线
	 * @param addr
	 * @param port
	 * @return
	 */
	public ListResponseResult handleStart(String addr, String port) {
		if (!StringUtils.isEmpty(addr) && !StringUtils.isEmpty(port)) {
			try {
				log.info("启动的时候获取到的url地址:"+"http://"+addr+":"+port+"/actuator/service-registry");
				RegistryPOJO registryVO = new RegistryPOJO();
				registryVO.setStatus("UP");
				String httpPost = HttpRequestUtils.httpPost("http://actuator:actuator@"+addr+":"+port+"/actuator/service-registry", SamJsonUtil.toJson(registryVO), "application/json");
				return getListResult(httpPost);
			} catch (Exception e){
				return getListResult(0, false);
			}
		}
		return getListResult(0, false);
	}
}
